package model

import (
	db "mwwow_service_go/database"
)

type User struct {
	Id       int    `json:"id",form:"userId"`
	Username string `json:"username",form:"username"`
	Password string `json:"password",form:"password"`
	Avatar   string `json:"avatar"`
}

type UserResponse struct {
	Id       int    `json:"id",form:"id"`
	Username string `json:"username",form:"username"`
	Avatar   string `json:"avatar"`
}

type UserInfo struct {
	Id        int    `json:"id",form:"id"`
	Username  string `json:"username",form:"username"`
	Nickname  string `json:"nickname"`
	Tags      string `json:"tags"`
	Address   string `json:"address"`
	Introduce string `json:"introduce"`
}

type Password struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

func (u *User) CheckLogin() (user UserResponse, isSuccess bool, err error) {
	sql := "SELECT id,username,avatar FROM user WHERE username=? AND password=MD5(?)"
	err = db.SqlDB.QueryRow(sql, u.Username, u.Password).Scan(&user.Id, &user.Username, &user.Avatar)
	if err != nil || user.Id == 0 {
		return
	}
	isSuccess = true
	return
}

func (u *User) GetUser() (users []UserInfo, err error) {
	sql := "SELECT id,username,nickname,tags,address,introduce FROM user NATURAL JOIN userInfo"
	rows, err := db.SqlDB.Query(sql)
	defer rows.Close()
	if err != nil {
		return
	}
	for rows.Next() {
		var user UserInfo
		rows.Scan(&user.Id, &user.Username, &user.Nickname, &user.Tags, &user.Address, &user.Introduce)
		users = append(users, user)
	}
	return
}

func (u *User) GetUserById(id string) (user UserInfo, err error) {
	user = UserInfo{}
	sql := "SELECT id,username,nickname,tags,address,introduce FROM user NATURAL JOIN userInfo WHERE id=?"
	err = db.SqlDB.QueryRow(sql, id).Scan(&user.Id, &user.Username, &user.Nickname,
		&user.Tags, &user.Address, &user.Introduce)
	if err != nil {
		return
	}
	return
}

func (p *Password) ChangePassword(id string) (isSuccess bool, err error) {
	sql := "SELECT id FROM user WHERE id=? AND password=MD5(?)"
	row := db.SqlDB.QueryRow(sql, id, p.OldPassword)
	var userId int
	row.Scan(&userId)
	if row == nil || userId == 0 {
		return
	}
	sql = "UPDATE user SET password=MD5(?) WHERE id=?"
	_, err = db.SqlDB.Exec(sql, p.NewPassword, id)
	if err != nil {
		return
	}
	isSuccess = true
	return
}
